Day 8 - Variables
29
$ x=5; echo ${x}
prints 5 on the terminal. You will often see people using a shorthand version of this syntax, which
avoids the the curly braces. That means that $x is most of the time the same as ${x}. My advice is to
get used to the full syntax now and never use the short one, as it can be confusing if underscores are
involved. I will dive into this is a later lesson, so for now do yourself and your fellow programmers
a favour and forget about the short notation. It’s just a pair of curly braces, after all, and using them
makes the code clearer.
You can use variables anywhere in bash, as they are replaced before commands get executed. For
example
$ x=5; sed -n ${x}p slices.txt
Arguably not the easiest syntax to read, but it is you who signed up for the course “Ancient spells and
mystical rituals”, after all. Wait a minute, what do you mean you just wanted to be a programmer?
What is the difference?
After variables, command substitution is one of the features you will use the most if you get into
bash scripting. Command substitution simply means that you assign to a variable the full output of
a command, and this is used often because it allows you to manipulate that output, to loop over its
parts, and in general to use it creatively.
Command substitution is expressed by the syntax $(command), where command is any line that you
could execute on the terminal. For example we might assign the output of a sequence to a variable
$ x=$(seq 1 5); echo ${x}
Please note that in this case the variable x gets the value of the string "1 2 3 4 5". It is not a list,
or any other complex data type, just a simple string made of digits and spaces. Bash automatically
converted the newline characters used by seq into spaces, and this will come in very handy when
we will learn how to write loops.
Cool, now enjoy the rest of the day, we will soon learn how to transform a pumpkin into a coach,
and mice into servants, just remember that at midnight everything goes back to text files.
Suggested film for the evening: A Beautiful Mind (2001) - A film about the importance of variables,
and the dangers of getting too involved in Unix scripting without having a good walk sometimes.